import operate from '@dfeidao/atom-nodejs/db/operate';
import query from '@dfeidao/atom-nodejs/db/query';
import doc_code from '@dfeidao/atom-nodejs/msg/doc-code';
import sys_date from '@dfeidao/atom-nodejs/msg/sys-date';
import uuid from 'uuid';
interface Message {
	filter1: {
		group_name: string;
		group_number: string;
		formname: string; // 功能名称
		package_no: string; // 页面编号
		package_name: string; // 页面名称
		package_path: string; // 页面地址
	};
	pub_form_code?: [];
	client_type: string;
	productid: string;
}
interface PubFormCode {
	code: string;			// 编码
	action_keyword: string;	// 控制点关键字
	action_name: string;	// 控制点名称

}
export default async function atom(msg: Message, action_id: string, session_id: string) {
	// 功能定义库 pub_form
	// 根据formname，package_no 判断是否重复
	const { exec, prepare } = query(action_id, session_id, '12');
	prepare('pub_form', ['_id'], { formname: msg.filter1.formname, group_number: msg.filter1.group_number, productid: msg.productid }, 200, 1, [], []);
	const [data] = await exec();
	if (data.length !== 0) {
		return 'repeat';
	}
	const no = await doc_code(action_id, session_id, '12', 'BM0015937', '', 1);
	const time = await sys_date(action_id, session_id);

	const { exec: e3, insert: p3 } = operate(action_id, session_id, '12');
	p3('pub_form', {
		_id: uuid(),
		group_name: msg.filter1.group_name,
		group_number: msg.filter1.group_number,
		client_type: msg.client_type, // 客户端类型	string
		package_no: msg.filter1.package_no, // 页面编号	string
		formid: no.results[0],// 功能号	string
		formname: msg.filter1.formname,	// 	功能名称	string
		create_time: time,// 创建时间	timestamp
		productid: msg.productid, // 产品ID	string
		package_name: msg.filter1.package_name, // 页面名称	string
		package_path: msg.filter1.package_path,// 页面地址	string
		source_flag: 0
	});
	// 功能定义控制点 pub_form_code
	if (msg.pub_form_code) {
		Array.from(msg.pub_form_code).forEach((v: PubFormCode) => {
			p3('pub_form_code', {
				_id: uuid(),
				formid: no.results[0],
				code: v.code,
				action_keyword: v.action_keyword,
				action_name: v.action_name,
				productid: msg.productid,
				source_flag: 0
			});
		});
	}
	const ret = await e3();
	if (ret.code === 1) {
		return 'success';
	} else {
		return 'fail';
	}
}
